from os import path,listdir

def FolderSize():
    SFolderPath = input("请输入一个文件夹的目录路径\n")
    if(path.exists(SFolderPath)):
        print("路径合法")
        print("正在计算文件夹\"%s\"的大小" % SFolderPath)
        # 规范path
        SFolderPath = path.normpath(SFolderPath)

        # 首次补全路径
        lt1 = listdir(SFolderPath)
        for i in range(0, len(lt1)):
            lt1[i] = path.join(SFolderPath, lt1[i])

        # print('lt1: %s' % lt1)
        FileSizeSum = 0
        lt2 = []
        lt2_temp = []
        times = 2  # 套路太深则警告并中断计算
        print('**************************** 计算开始 ****************************')
        while (len(lt1) > 0 and times > 0):
            # 遇文件则算大小，遇夹则先记录内容，下次处理
            for i in lt1:
                if path.isfile(i):
                    FileSizeSum += path.getsize(i)
                    print('文件： %s 大小:%d' % (i, path.getsize(i)))

                else:
                    lt2_temp = (listdir(i))
                    # print('lt2_temp: %s' % lt2_temp)
                    for j in range(0, len(lt2_temp)):
                        lt2_temp[j] = path.join(i, lt2_temp[j])
                    lt2.extend(lt2_temp)
                    lt2_temp.clear()
                    print('已搜索到：%s \n已缓存的次级目录: %s' % (i, lt2))

            # print('清除：lt1  %d 次' % times)
            lt1.clear()  # 清除已处理的目录1
            lt1.extend(lt2)
            lt2.clear()  # 清除已处理的目录2
            # print('lt1现状：%s' % lt1)
            times -= 1
            # print('times = %d , len(lt1) = %d ' % (times,len(lt1) ))
        if (times == 0 and len(lt1) != 0):
            print('水太深,算不下去了,暂时已经计算的大小为:\n %d B' % FileSizeSum)
        else:
            print('计算完成,总文件大小为:\n{0:,} B'.format(FileSizeSum))
        return
    else:
        print('请使用合法的路径重试!!!')
        return



